package me.zhengjie.modules.utils;

import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.utils.FileUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Map;

/**
 * @author CN-xianchengzhao
 * @description: TODO
 * @date 2021/12/8 22:00
 */
@Slf4j
@Component
public class CreateExportHtmlUtil {

    @Async
    public void export(Template template, Map<String, Object> root, String outFile) {
        FileWriter out = null;
        try {
            root.remove("advertList");
            String[] strAttr = outFile.split("\\.");
            String pattern = "{0}_{1}.{2}";
            String tmpPath = MessageFormat.format(pattern,strAttr[0],"export",strAttr[1]);
            File html = FileUtil.getFile(tmpPath).getCanonicalFile();
            // 通过一个文件输出流，就可以写到相应的文件中，此处用的是绝对路径
            out = new FileWriter(html);
            template.process(root, out);
        } catch (Exception e){
            log.error("生成导出html异常",e);
        }finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
